<?php

include_once dirname(__FILE__). '/AController.php';

class AdvController extends AController
{
	public $defaultAction = 'list';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	public function actionList($type) {
		$arr =  array(
			'pagination' => array('pageSize' => 20),
			'criteria' => array(
				'condition' => "type='{$type}'"
			)
		);
		$dataProvider = new CActiveDataProvider('Adv', $arr);
		$data = array();
		foreach ($dataProvider->data as $k => $v) {
			if (!empty($v->data)) {
				$d = unserialize($v->data);
				if ($d['width'] > 150 && $d['width'] > $d['height']) {
					$d['img_size'] = "width=150";
				} else if ($d['height'] > 80 && $d['height'] > $data['width']) {
					$d['img_size'] = "height=100";
				}
				$v->data = $d;
			}
			$data[$k] = $v;
		}
		$dataProvider->setData($data);
		
		$block_title = $type=='banner'? 'Banner广告' : '文字广告管理';
		
		$params = array(
			'dataProvider' => $dataProvider, 
			'block_title' => $block_title, 
			'type' => $type
		);
		$this->render('list', $params);
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($type)
	{
		$model=new Adv;
		$model->type = $type;
		$this->create($model);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$model->data = unserialize($model->data);
		$this->create($model);
	}
	
	protected function create($model) {
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$type = $model->type;

		if(isset($_POST['Adv']))
		{
			$data = $_POST['Adv'];
			
			$model->url = $data['url'];
			$model->type = $type;
			$model->created = time();
			$website = Website::model()->findByPk($_POST['Adv']['website_id']);
			$model->website_id = $data['website_id'];
			$model->website = $website->domain;
			if ($type == 'banner') {
				$upload = CUploadedFile::getInstance($model, 'src');
				if (!empty($upload)) {
					$file_name = 'uploads/bn/'. date('Ymdhis') . mt_rand(1000, 2000) .".". $upload->extensionName;
					$upload->saveAs($file_name);
					$data['data']['src'] = $file_name;
					$data['data']['thumb'] = thumb($file_name);
					
					include_once("protected/phpthumb/ThumbLib.inc.php");
					$image = PhpThumbFactory::create($file_name);
					$size = $image->getCurrentDimensions();
					$data['data']['width'] = $size['width'];
					$data['data']['height'] = $size['height'];
				} else {
					$data['data']['src'] = $model->data['src'];
					$data['data']['size'] = $model->data['size'];
				}
			} 
			
			$model->data = serialize($data['data']);
			
			if($model->save()) {
				$this->redirect(array('/admin/adv', 'type' => $type));
			}
		}
		
		$this->render('create', array('model'=>$model, 'type' => $type));
	}
	
	protected function getWebsites() {
		$wb = Website::model()->findAll();
		$websites = array();
		foreach ($wb as $w) {
			$websites[$w['website_id']] = $w['domain'];
		}
		return $websites;
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($type)
	{
		if (!empty($_POST['advs'])) {
			foreach ($_POST['advs'] as $k => $id) {
				$this->loadModel($id)->delete();
			}
		}
		$this->redirect(array('/admin/adv', 'type' => $type));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Adv');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Adv('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Adv']))
			$model->attributes=$_GET['Adv'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Adv::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='adv-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
